﻿#include "networkconfig.h"

#include <QDebug>

namespace Common {

	NetworkConfig::NetworkConfig(QObject *parent)
		: QObject(parent)
	{

	}

	NetworkConfig::~NetworkConfig()
	{

	}

	QString NetworkConfig::getHostName()
	{
		return QHostInfo::localHostName();
	}

	QString NetworkConfig::getLocalIP()
	{
		QString localName = QHostInfo::localHostName();

		QHostInfo hostInfo = QHostInfo::fromName(localName);

		QList<QHostAddress> addrList = hostInfo.addresses();

		QString localIP = "";
		if (!addrList.isEmpty())
		{
			for (int i = 0; i < addrList.size(); i++)
			{
				QHostAddress addr = addrList.at(i);
				if (QAbstractSocket::IPv4Protocol == addr.protocol())
				{
					localIP = addr.toString();
					break;
				}
			}
		}
		return localIP;
	}

	QStringList NetworkConfig::getIpList(QString strHostName)
	{
		QHostInfo info = QHostInfo::fromName(strHostName);

		if (info.error() != QHostInfo::NoError)
		{
			return QStringList();
		}
		QStringList list;
		const auto addresses = info.addresses();
		for (const QHostAddress &address : addresses)
		{
			qDebug() << "address:" << address.toString() << "  hostname:" << info.hostName();
			list.append(address.toString());
		}

		return list;
	}

}// namespace Common
